package com.company.woye.console.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.company.woye.MyApplication;
import com.company.woye.R;
import com.company.woye.base.BaseActivity;
import com.company.woye.checkmakesure.MakeSureCheckActivity;
import com.company.woye.checkscan.CheckScanActivity;
import com.company.woye.console.adapter.LoadTXMAdapter;
import com.company.woye.console.adapter.SingleDetailListviewAdapter;
import com.company.woye.console.entity.LoadTXMEntity;
import com.company.woye.console.entity.PowerBean;
import com.company.woye.console.entity.SingleDetailEntity;
import com.company.woye.quantitycheck.QuantityCheck2Activity;
import com.company.woye.readycommit.ReadyCommitActivity;
import com.company.woye.taiorcheckSize.TaiorCheckSizeActivity;
import com.company.woye.taiorcheckquestion.TaiorCheckQuestionActivity;
import com.company.woye.utils.BasePopupWindow;
import com.company.woye.utils.BaseRequest;
import com.company.woye.utils.DBUtil;
import com.company.woye.utils.MyBorderTextView;
import com.company.woye.utils.ScannerManager;
import com.company.woye.utils.SharedPreferenceUtils;
import com.company.woye.utils.Toaster;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

import static com.company.woye.utils.BaseRequest.postJsonData;

/**
 * 检验台
 */
public class CheckoutConsoleActivity extends BaseActivity implements LoadTXMAdapter.OnItemClickListener, Runnable {

    private static final String TAG = CheckoutConsoleActivity.class.getSimpleName();
    String PrBarcode = "";
    @BindView(R.id.mainFrame)
    FrameLayout mainFrame;
    @BindView(R.id.edit_Barcode)
    EditText editBarcode;
    @BindView(R.id.tv_tiao_xing_ma)
    TextView tv_tiao_xing_ma;
    @BindView(R.id.tv_checkout_box_num_show)
    TextView tv_checkout_box_num_show;

    @BindView(R.id.tv_refresh_boxnumber)
    TextView tv_refresh_boxnumber;


    @BindView(R.id.bbm)
    TextView bbm;
    @BindView(R.id.dDate)
    TextView dDate;

    @BindView(R.id.StyleNo)
    TextView StyleNo;

    @BindView(R.id.DBH)
    TextView DBH;
    @BindView(R.id.OrderNo)
    TextView OrderNo;
    @BindView(R.id.PO)
    TextView PO;

    @BindView(R.id.StyleSort)
    TextView StyleSort;

    @BindView(R.id.pssh)
    TextView pssh;

    @BindView(R.id.Color)
    TextView Color;
    @BindView(R.id.ColorNo)
    TextView ColorNo;

    @BindView(R.id.Number)
    TextView Number;

    @BindView(R.id.SIZE)
    TextView SIZE;
    @BindView(R.id.SumPackNum)
    TextView SumPackNum;
    @BindView(R.id.SumScanPackNum)
    TextView SumScanPackNum;

    @BindView(R.id.SumPackNumber)
    TextView SumPackNumber;

    @BindView(R.id.SumScanPackNumber)
    TextView SumScanPackNumber;

    @BindView(R.id.ResultInfo)
    TextView ResultInfo;

    @BindView(R.id.rcl_checkout_console)
    RecyclerView mListView;

    @BindView(R.id.tv_type)
    TextView tv_type;

    @BindView(R.id.tv_type_name)
    TextView tv_type_name;


    @BindView(R.id.tv_left)
    TextView tv_left;

    @BindView(R.id.tv_right)
    TextView tv_right;

    @BindView(R.id.iv_automatic_identification)
    ImageView iv_automatic_identification;

    @BindView(R.id.tv_default_flower)
    TextView tv_default_flower;


    @BindView(R.id.tv_one_one)
    TextView tv_one_one;

    @BindView(R.id.tv_one_two)
    TextView tv_one_two;

    @BindView(R.id.tv_three)
    TextView tv_three;

    @BindView(R.id.tv_four)
    TextView tv_four;

    @BindView(R.id.tv_checkout_in_wei_qi)
    TextView tv_checkout_in_wei_qi;

    @BindView(R.id.tv_checkout_box_internal_num_show)
    TextView tv_checkout_box_internal_num_show;
    @BindView(R.id.tv_two)
    TextView tv_two;

    @BindView(R.id.iv_conventional_remind)
    ImageView iv_conventional_remind;

    @BindView(R.id.admin)
    RadioButton rbAdmin;

    @BindView(R.id.lv_single)
    ListView lv_single;

    @BindView(R.id.tv_runState)
    TextView tv_runState;

    List<LoadTXMEntity> detailList = new ArrayList<>();
    @BindView(R.id.iv_checkout_console_back)
    TextView ivCheckoutConsoleBack;
    @BindView(R.id.tv_look_state)
    TextView tvLookState;
    @BindView(R.id.tv_checkout_out_bound)
    TextView tvCheckoutOutBound;
    @BindView(R.id.tv_checkout_single_number)
    TextView tvCheckoutSingleNumber;
    @BindView(R.id.tv_checkout_box_operation)
    TextView tvCheckoutBoxOperation;
    @BindView(R.id.tv_checkout_question_number)
    TextView tvCheckoutQuestionNumber;
    @BindView(R.id.tv_checkout_exception)
    TextView tvCheckoutException;
    @BindView(R.id.tv_check_sure)
    TextView tvCheckSure;
    @BindView(R.id.tv_ready_commit)
    TextView tvReadyCommit;
    @BindView(R.id.tv_check_scan)
    TextView tvCheckScan;
    @BindView(R.id.bt_sure_barcode)
    Button btSureBarcode;
    @BindView(R.id.tv_checkout_box_num)
    TextView tvCheckoutBoxNum;
    @BindView(R.id.tv_checkout_box_internal_num)
    TextView tvCheckoutBoxInternalNum;
    @BindView(R.id.tv_checkout_box)
    TextView tvCheckoutBox;
    @BindView(R.id.tech)
    RadioButton tech;
    @BindView(R.id.rg_checkout)
    RadioGroup rgCheckout;
    @BindView(R.id.tv_clear_box)
    TextView tvClearBox;
    @BindView(R.id.tv_conventional_remind)
    TextView tvConventionalRemind;
    @BindView(R.id.ll_conventional_remind)
    LinearLayout llConventionalRemind;
    @BindView(R.id.tv_checkout_in)
    MyBorderTextView tvCheckoutIn;
    @BindView(R.id.tv_automatic_identification)
    TextView tvAutomaticIdentification;
    @BindView(R.id.tv_beici)
    MyBorderTextView tvBeici;
    @BindView(R.id.tv_sure)
    MyBorderTextView tvSure;
    //全局变量
    private ProgressDialog waitDialog = null;
    private BasePopupWindow popupWindow;
    View inflaterView;
    static Drawable drawable_gray, drawable_green, drawable_red;

    boolean ScanSign = false;
    String FormType = "", curLoginUserNo = "";
    private final static int MSG_AllowScan = 9000;
    private final static int MSG_FocusBarcode = 9001;
    private final static int MSG_GET_BOX_NUM = 9002;
    private final static int MSG_CLEAR_BARCODE = 9003;
    private final static int MSG_CLEAR_BOX = 9004;
    private final static int MSG_GET_ALL_BOX_NUM = 9005;
    private static final int MSG_CallAgvResult = 9007;
    private static final int MSG_AgvCallInfoTrans = 9008;
    private static final int MSG_GetBoxNum = 9009;
    private static final int MSG_GetSingINFO = 9010;
    private static final int MSG_SaveError = 9011;
    private static final int MSG_ERROR = 9012;
    private static final int MsgGetPower = 9013;
    MyBorderTextView btnView;

    private JSONArray powerJson, detailJSON, TXMdetailJSON, RKdetailJSON;
    private ScannerManager scannerManager;
    private String CurStationNo;

    private SingleDetailListviewAdapter singleDetailListviewAdapter;
    private String TaskID;
    private String defaultName = "", isAuto = "1", isBind, isRemind, prBoxNum = "";
    private boolean NeedReGetBox = false, ExitSign = false;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (scannerManager.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_checkout_console;
    }

    @Override
    public void initView() {

        //状态背景颜色
        drawable_gray = getResources().getDrawable(R.drawable.round_gray_background);
        drawable_green = getResources().getDrawable(R.drawable.round_green_background);
        drawable_red = getResources().getDrawable(R.drawable.round_red_background);
        //登录返回的参数
        FormType = TAG;
        curLoginUserNo = MyApplication.curLoginUserNo;
        String left = (String) SharedPreferenceUtils.getData(sharedPreferences, "leftGongWei", "");
        tv_left.setText("左工位号" + left);
        String right = (String) SharedPreferenceUtils.getData(sharedPreferences, "rightGongWei", "");
        tv_right.setText("右工位号" + right);
        if (((String) SharedPreferenceUtils.getData(sharedPreferences, "nowGongWei", "0")).equals("0")) {
            CurStationNo = (String) SharedPreferenceUtils.getData(sharedPreferences, "leftGongWei", "");
            tv_left.setBackgroundResource(R.color.lightGreen);
            tv_right.setBackgroundResource(R.color.Green);
            tv_left.setText("左工位号" + CurStationNo);
        } else {
            CurStationNo = (String) SharedPreferenceUtils.getData(sharedPreferences, "rightGongWei", "");
            tv_left.setBackgroundResource(R.color.Green);
            tv_right.setBackgroundResource(R.color.lightGreen);
            tv_right.setText("右工位号" + CurStationNo);
        }
        if (!((String) SharedPreferenceUtils.getData(sharedPreferences, "defaultName", "")).isEmpty()) {
            defaultName = (String) SharedPreferenceUtils.getData(sharedPreferences, "defaultName", "");
            tv_default_flower.setText("默认出口:" + defaultName);
        } else {
            defaultName = "出口1-1花片";
        }
        isAuto = "1";
        isBind = "1";
        isRemind = "1";
        iv_conventional_remind.setImageResource(R.drawable.xuanzhong);
        tv_default_flower.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        editBarcode.setInputType(InputType.TYPE_NULL);
        editBarcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editBarcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(editBarcode, InputMethodManager.SHOW_FORCED);
            }
        });
        editBarcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null) {
                    Log.e("Debug", "-----------------------------Debug-----------------------------");
                    //System.out.println(event);
                    if ((event.getAction() == KeyEvent.ACTION_UP) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        System.out.println(editBarcode.getText().toString());
                        ScanBarcode();
                        return true;
                    }
                }
                return false;
            }
        });
        editBarcode.requestFocus();
        editBarcode.requestFocusFromTouch();
        //拦截扫描事件

        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
            @Override
            public void onResult(String code, String deviceName) {
                Log.d(TAG, "code= " + code);
                String nowCode = dealCode(code).trim();
                editBarcode.setText(nowCode);
                ScanBarcode();
            }
        }, editBarcode.getContext());
        System.out.println("创建waitDialog----Start");
        //创建对话框，
        waitDialog = new ProgressDialog(CheckoutConsoleActivity.this);
        waitDialog.setTitle("请稍等");
        waitDialog.setIndeterminate(true);
        System.out.println("创建waitDialog----Over");
        //初始化界面按钮
        initButton(curLoginUserNo, left);


    }


    @OnClick({R.id.tv_check_scan, R.id.tv_checkout_question_number, R.id.tv_check_sure, R.id.tv_ready_commit, R.id.tv_beici, R.id.tv_checkout_out_bound, R.id.tv_checkout_single_number, R.id.tv_checkout_box_operation,
            R.id.tv_checkout_exception, R.id.tv_checkout_in, R.id.iv_checkout_console_back, R.id.bt_sure_barcode,
            R.id.tech, R.id.tv_clear_box, R.id.tv_one_one, R.id.tv_one_two, R.id.tv_two, R.id.tv_three, R.id.tv_four,
            R.id.tv_checkout_in_wei_qi, R.id.tv_sure, R.id.tv_left, R.id.tv_right, R.id.iv_automatic_identification,
            R.id.tv_automatic_identification, R.id.tv_default_flower, R.id.admin, R.id.ll_conventional_remind})
    public void onViewClick(View view) {
        if (btnView != null && view.getClass() == btnView.getClass()) {
            btnView = (MyBorderTextView) view;
            btnView.setEnabled(false);
        }
        AlertDialog.Builder dialog;
        switch (view.getId()) {
            //备次出口
            case R.id.tv_beici:
                String boxnum = tv_checkout_box_num_show.getText().toString();
                if (!TextUtils.isEmpty(boxnum)) {
                    ruKu("备次出口");
                } else {
                    Toaster.showLong(CheckoutConsoleActivity.this, "请先扫描箱号");
                }
                break;
            //检验扫描
            case R.id.tv_check_scan:
                startActivity(new Intent(CheckoutConsoleActivity.this, CheckScanActivity.class));
                break;
            //备次提交
            case R.id.tv_ready_commit:
                startActivity(new Intent(CheckoutConsoleActivity.this, ReadyCommitActivity.class));
                break;
            //检验确认
            case R.id.tv_check_sure:
                startActivity(new Intent(CheckoutConsoleActivity.this, MakeSureCheckActivity.class));
                break;
            case R.id.tv_refresh_boxnumber:
                System.out.println("tv_refresh_boxnumber:Enter");
                prBoxNum = tv_checkout_box_num_show.getText().toString();
                tv_checkout_box_num_show.setText("");
                NeedReGetBox = true;

                break;
            case R.id.tv_checkout_out_bound:
                startActivity(new Intent(this, OutBoundActivity.class));
                break;
            case R.id.tv_checkout_single_number:
                startActivity(new Intent(this, SingleNumberActivity.class));
                break;
            //裁剪检验
            //裁剪验片尺寸
            case R.id.tv_checkout_box_operation:
//                startActivity(new Intent(this, TailorCheckActivity.class));
                startActivity(new Intent(this, TaiorCheckSizeActivity.class));
                break;
            //裁剪验片疵点
            case R.id.tv_checkout_question_number:
                startActivity(new Intent(this, TaiorCheckQuestionActivity.class));
                break;
            //质量检验
            case R.id.tv_checkout_exception:
//                startActivity(new Intent(this, QuantityCheck2Activity.class));
//                checkExceptionTextViewOnClick();
                break;
            case R.id.iv_checkout_console_back:
                finish();
                break;
            case R.id.bt_sure_barcode:
                ScanBarcode();
                break;
            case R.id.admin:
                isBind = "1";
                //ScanBarcode();
                break;
            case R.id.tech:
                isBind = "0";
                //ScanBarcode();
                break;
            case R.id.tv_clear_box:
                dialog = new AlertDialog.Builder(CheckoutConsoleActivity.this);
                dialog.setTitle("提示");
                dialog.setMessage("是否确定清空");
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        clearBox();
                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
                dialog.show();
                break;
            case R.id.tv_one_one:
                if (isAuto.equals("1")) {
                    Toaster.showLong(CheckoutConsoleActivity.this, "请先取消勾选自动识别出口");
                    return;
                }
                if (tv_checkout_box_num_show.getText().toString().isEmpty()) {
                    Toast.makeText(this, "箱条码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                ruKu("出口1-1 印花");//对应1-1 花片口
                //ruKu("出口1-1花片");

                break;
            case R.id.tv_one_two:
                if (isAuto.equals("1")) {
                    Toaster.showLong(CheckoutConsoleActivity.this, "请先取消勾选自动识别出口");
                    return;
                }
                if (tv_checkout_box_num_show.getText().toString().isEmpty()) {
                    Toast.makeText(this, "箱条码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                ruKu("出口1-2 绣花");//对应1-2 十字架
                //ruKu("出口1-2花片");

                break;
            case R.id.tv_two:
                if (isAuto.equals("1")) {
                    Toaster.showLong(CheckoutConsoleActivity.this, "请先取消勾选自动识别出口");
                    return;
                }
                if (tv_checkout_box_num_show.getText().toString().isEmpty()) {
                    Toast.makeText(this, "箱条码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                ruKu("出口2花片");

                break;
            case R.id.tv_three:
                if (isAuto.equals("1")) {
                    Toaster.showLong(CheckoutConsoleActivity.this, "请先取消勾选自动识别出口");
                    return;
                }
                if (tv_checkout_box_num_show.getText().toString().isEmpty()) {
                    Toast.makeText(this, "箱条码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                ruKu("出口3热转印");

                break;
            case R.id.tv_four:
                if (isAuto.equals("1")) {
                    Toaster.showLong(CheckoutConsoleActivity.this, "请先取消勾选自动识别出口");
                    return;
                }
                if (tv_checkout_box_num_show.getText().toString().isEmpty()) {
                    Toast.makeText(this, "条形码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                ruKu("出口4螺纹烫衬");

                break;
            case R.id.tv_checkout_in:
                if (isAuto.equals("1")) {
                    Toaster.showLong(CheckoutConsoleActivity.this, "请先取消勾选自动识别出口");
                    return;
                }
                if (tv_checkout_box_num_show.getText().toString().isEmpty()) {
                    Toast.makeText(this, "箱条码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                ruKu("入库");

                break;
            case R.id.tv_checkout_in_wei_qi:
                if (tv_checkout_box_num_show.getText().toString().isEmpty()) {
                    Toast.makeText(this, "箱条码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                dialog = new AlertDialog.Builder(CheckoutConsoleActivity.this);
                dialog.setTitle("提示");
                dialog.setMessage("确定要将花片未齐入库吗?");
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ruKu("花片未齐入库");
                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
                dialog.show();

                break;
            case R.id.tv_sure:
                if (isAuto.equals("0")) {
                    Toaster.showLong(CheckoutConsoleActivity.this, "请先勾选自动识别出口");
                    return;
                }
                if (tv_checkout_box_num_show.getText().toString().isEmpty()) {
                    Toast.makeText(this, "箱条码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                ruKu("确认");
                break;
            case R.id.tv_left:
                CurStationNo = (String) SharedPreferenceUtils.getData(sharedPreferences, "leftGongWei", "");
                SharedPreferenceUtils.putData(sharedPreferences, "nowGongWei", "0");
                tv_left.setBackgroundResource(R.color.lightGreen);
                tv_right.setBackgroundResource(R.color.Green);
                clearButton();
                if (!TextUtils.isEmpty(tv_checkout_box_num_show.getText().toString().trim())) {
                    NeedReGetBox = true;
                }
                break;
            case R.id.tv_right:
                CurStationNo = (String) SharedPreferenceUtils.getData(sharedPreferences, "rightGongWei", "");
                SharedPreferenceUtils.putData(sharedPreferences, "nowGongWei", "1");
                tv_left.setBackgroundResource(R.color.Green);
                tv_right.setBackgroundResource(R.color.lightGreen);
                clearButton();
                if (!TextUtils.isEmpty(tv_checkout_box_num_show.getText().toString().trim())) {
                    NeedReGetBox = true;
                }
                break;
            case R.id.iv_automatic_identification:
            case R.id.tv_automatic_identification:
                if (isAuto.equals("1")) {
                    isAuto = "0";
                    iv_automatic_identification.setBackgroundResource(R.drawable.weixuan);
                } else {
                    isAuto = "1";
                    iv_automatic_identification.setBackgroundResource(R.drawable.xuanzhong);
                }

                break;
//            case R.id.tv_default_flower:
//                showDefault();
//                break;
            case R.id.ll_conventional_remind:
                if (isRemind.equals("0")) {
                    isRemind = "1";
                    iv_conventional_remind.setImageResource(R.drawable.xuanzhong);
                } else {
                    isRemind = "0";
                    iv_conventional_remind.setImageResource(R.drawable.weixuan);
                }
                break;


        }
    }


    private void initButton(String userNo, String leftNo) {
        //界面按钮全关;
        tv_one_one.setVisibility(View.INVISIBLE);
        tv_one_two.setVisibility(View.INVISIBLE);
        tv_two.setVisibility(View.INVISIBLE);
        tv_three.setVisibility(View.INVISIBLE);
        tv_four.setVisibility(View.INVISIBLE);
        tvCheckoutIn.setVisibility(View.INVISIBLE);
        tvBeici.setVisibility(View.INVISIBLE);
        tv_checkout_in_wei_qi.setVisibility(View.INVISIBLE);
        tvSure.setVisibility(View.INVISIBLE);
        String sql = "EXEC [AGV_Check_Obtain_Func] @UserNo='" + userNo + "',@LeftNo='" + leftNo + "',@OperType='getPower'";
        ReadSQLData(sql, MsgGetPower);

    }

    private void clearButton() {
        isBind = "1";
        rbAdmin.setChecked(true);
        editBarcode.setText("");
        tv_tiao_xing_ma.setText("");
        tv_checkout_box_num_show.setText("");
        bbm.setText("");
        dDate.setText("");

        StyleNo.setText("");
        DBH.setText("");
        OrderNo.setText("");
        PO.setText("");
        StyleSort.setText("");

        pssh.setText("");
        Color.setText("");
        ColorNo.setText("");
        Number.setText("");
        SIZE.setText("");

        SumPackNum.setText("");
        SumScanPackNum.setText("");
        SumPackNumber.setText("");
        SumScanPackNumber.setText("");
        ResultInfo.setText("");

        tv_type.setText("");
        tv_checkout_box_internal_num_show.setText("");
        mListView.setAdapter(null);
        lv_single.setAdapter(null);


    }

    private void checkExceptionTextViewOnClick() {
        View view = LayoutInflater.from(this).inflate(R.layout.popupwindow_out_bound, null);
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();
        final PopupWindow popupWindow = new PopupWindow(view, width / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        ImageView back = view.findViewById(R.id.iv_out_bound_back);
        TextView top = view.findViewById(R.id.tv_pop_top_left);
        TextView hint1 = view.findViewById(R.id.tv_pop_hint1);
        TextView hint2 = view.findViewById(R.id.tv_pop_hint2);
        TextView hint3 = view.findViewById(R.id.tv_pop_hint3);
        TextView pause = view.findViewById(R.id.tv_pop_pause);
        TextView resume = view.findViewById(R.id.tv_pop_resume);
        EditText editText = view.findViewById(R.id.et_pop);
        editText.setVisibility(View.VISIBLE);
        back.setOnClickListener(v -> {
            popupWindow.dismiss();
        });
        top.setText("异常备注");
        hint1.setVisibility(View.GONE);
        hint2.setVisibility(View.GONE);
        hint3.setVisibility(View.GONE);
        hint1.setText("");
        hint2.setText("");
        pause.setBackgroundResource(R.drawable.stroke_blue);
        pause.setTextColor(getResources().getColor(R.color.blue));
        resume.setBackgroundResource(R.drawable.button_primary_shape);
        hint3.setText("");
        pause.setText("取消");
        resume.setText("确定");
        resume.setOnClickListener(v -> {
            popupWindow.dismiss();
        });
        pause.setOnClickListener(v -> {
            popupWindow.dismiss();
        });
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    private void inBoundTextViewOnClick() {
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();
        View view = LayoutInflater.from(this).inflate(R.layout.popupwindow_out_bound, null);
        final PopupWindow popupWindow = new PopupWindow(view, width / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        ImageView back = view.findViewById(R.id.iv_out_bound_back);
        TextView top = view.findViewById(R.id.tv_pop_top_left);
        TextView hint1 = view.findViewById(R.id.tv_pop_hint1);
        TextView hint2 = view.findViewById(R.id.tv_pop_hint2);
        TextView hint3 = view.findViewById(R.id.tv_pop_hint3);
        TextView pause = view.findViewById(R.id.tv_pop_pause);
        TextView resume = view.findViewById(R.id.tv_pop_resume);
        back.setOnClickListener(v -> {
            popupWindow.dismiss();
        });
        pause.setVisibility(View.VISIBLE);
        pause.setBackgroundResource(R.drawable.stroke_blue);
        resume.setBackgroundResource(R.drawable.stroke_blue);
        pause.setTextColor(getResources().getColor(R.color.blue));
        resume.setTextColor(getResources().getColor(R.color.blue));
        top.setText("空箱操作");
        hint1.setText("");
        hint2.setText("请选择哪种空箱入库：");
        hint3.setText("");
        pause.setText("空料箱");
        resume.setText("箱（含小箱）");
        resume.setOnClickListener(v -> {
        });
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }


    private void showDefault() {
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();
        View view = LayoutInflater.from(this).inflate(R.layout.popupwindow_flower, null);
        final PopupWindow popupWindow = new PopupWindow(view, width / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        ImageView back = view.findViewById(R.id.iv_out_bound_back);
        RadioButton hint1 = view.findViewById(R.id.admin);
        hint1.setChecked(defaultName.equals("出口1-1 印花"));
        hint1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                defaultName = "出口1-1 印花";
                SharedPreferenceUtils.putData(sharedPreferences, "defaultName", defaultName);
                tv_default_flower.setText("默认出口:" + defaultName);
                popupWindow.dismiss();
            }
        });
        RadioButton hint2 = view.findViewById(R.id.tech);
        hint1.setChecked(defaultName.equals("出口1-2 绣花"));
        hint2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                defaultName = "出口1-2 绣花";
                SharedPreferenceUtils.putData(sharedPreferences, "defaultName", defaultName);
                tv_default_flower.setText("默认出口:" + defaultName);
                popupWindow.dismiss();
            }
        });
        RadioButton hint3 = view.findViewById(R.id.tv_three);
        hint3.setChecked(defaultName.equals("出口2花片"));
        hint3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                defaultName = "出口2花片";
                SharedPreferenceUtils.putData(sharedPreferences, "defaultName", defaultName);
                tv_default_flower.setText("默认出口:" + defaultName);
                popupWindow.dismiss();
            }
        });

        if (MyApplication.Bbm.contains("二") || MyApplication.Bbm.contains("2")) {
            hint1.setVisibility(View.VISIBLE);
            hint2.setVisibility(View.VISIBLE);
            hint1.setChecked(true);
        } else {
            hint1.setVisibility(View.GONE);
            hint2.setVisibility(View.GONE);
            hint3.setChecked(true);
        }

        back.setOnClickListener(v -> {
            popupWindow.dismiss();
        });
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }


    private void getBoxNum() {
        if (tv_runState.getBackground().equals(drawable_red))
            tv_runState.setBackground(drawable_gray);
        else tv_runState.setBackground(drawable_red);

        //--EXEC AGV_Check_CutInScanBarcode @Barcode='',@FormType='',@BoxNo='',@OperType='LoadBoxNo',@UserNo='89898989'
        String SqlComm = "Exec AGV_Check_CutInScanBarcode @Barcode='',@CurStationNo='" + CurStationNo + "',@FormType='" + FormType
                + "',@BoxNo='" + tv_checkout_box_num_show.getText().toString()
                + "',@OperType='" + "LoadBoxNo" + "',@UserNo='" + MyApplication.curLoginUserNo + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm, MSG_GET_BOX_NUM);
    }

    private void ScanBarcode() {
        if (editBarcode.getText().toString().isEmpty()) {
            Toast.makeText(this, "条形码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        hideIM(editBarcode);
        if (ScanSign == false) {
            ScanSign = true;
            //组织WebService地址;

            editBarcode.setEnabled(false);
//            --EXEC AGV_Check_CutInScanBarcode @Barcode='',@FormType='',@BoxNo='',@OperType='LoadBoxNo',@UserNo='89898989'
            String SqlComm = "Exec AGV_Check_CutInScanBarcode @Barcode='" + editBarcode.getText().toString() + "',@PrBarcode='" + PrBarcode
                    + "',@CurStationNo='" + CurStationNo + "',@IsBind='" + isBind + "',@IsMixedReminder='" + isRemind
                    + "',@FormType='" + FormType + "',@BoxNo='" + tv_checkout_box_num_show.getText().toString() + "',@OperType='" + "ScanBarcode" + "',@UserNo='" + MyApplication.curLoginUserNo + "'";
            PrBarcode = editBarcode.getText().toString();
            Log.e(TAG, SqlComm);

            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm, MSG_FocusBarcode);
        } else Toast.makeText(this, "请稍等或退出重进!", Toast.LENGTH_LONG).show();
    }


    private void SaveError(String paramError) {
        String SqlComm = "Exec AGV_Check_CutInScanBarcode @Barcode='" + editBarcode.getText().toString() + "',@PrBarcode='" + PrBarcode
                + "',@CurStationNo='" + CurStationNo + "',@IsBind='" + isBind + "',@IsMixedReminder='" + isRemind
                + "',@FormType='" + FormType + "',@BoxNo='" + tv_checkout_box_num_show.getText().toString()
                + "',@OperType='" + "SaveError" + "',@UserNo='" + MyApplication.curLoginUserNo + "',@ErrorInfo='" + paramError + "'";
        Log.e(TAG, SqlComm);
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm, MSG_SaveError);
    }

    private void clearBarcode(String TXM) {
        if (tv_checkout_box_num_show.getText().toString().isEmpty()) {
            Toast.makeText(this, "箱号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        hideIM(editBarcode);
        editBarcode.setEnabled(false);
        String SqlComm = "Exec AGV_Check_CutInScanBarcode @TXM='" + TXM + "',@CurStationNo='" + CurStationNo + "',@FormType='" + FormType + "',@BoxNo='" + tv_checkout_box_num_show.getText().toString() + "',@OperType='" + "DelBarcode" + "',@UserNo='" + MyApplication.curLoginUserNo + "'";
        Log.e(TAG, SqlComm);
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm, MSG_CLEAR_BARCODE);
    }

    private void clearBox() {
        hideIM(editBarcode);
        editBarcode.setEnabled(false);
        String SqlComm = "Exec AGV_Check_CutInScanBarcode @FormType='" + FormType + "',@CurStationNo='" + CurStationNo + "',@BoxNo='" + tv_checkout_box_num_show.getText().toString() + "',@OperType='" + "ClearBarcode" + "',@UserNo='" + MyApplication.curLoginUserNo + "'";
        Log.e(TAG, SqlComm);
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm, MSG_CLEAR_BOX);
    }

    //--获取所有条码
    //--EXEC AGV_Check_CutInScanBarcode  @FormType='',@BoxNo='',@OperType='LoadTXM',@UserNo='89898989'
    private void searchAllCode() {
        if (tv_checkout_box_num_show.getText().toString().isEmpty()) {
            return;
        }
        hideIM(editBarcode);
        editBarcode.setEnabled(false);

        String SqlComm = "Exec AGV_Check_CutInScanBarcode @FormType='" + FormType + "',@PrBarcode='" + PrBarcode
                + "',@CurStationNo='" + CurStationNo + "',@BoxNo='" + tv_checkout_box_num_show.getText().toString()
                + "',@OperType='" + "LoadTXM" + "',@UserNo='" + MyApplication.curLoginUserNo + "'";
        Log.e(TAG, SqlComm);
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm, MSG_GET_ALL_BOX_NUM);
    }

    private void getSingleInfo() {
        lv_single.setAdapter(null);
        hideIM(editBarcode);
        editBarcode.setEnabled(false);
        String SqlComm = "Exec AGV_Check_CutInScanBarcode @Barcode='" + editBarcode.getText().toString() + "',@BoxNo='"
                + tv_checkout_box_num_show.getText().toString()
                + "',@FormType='" + FormType
                + "',@OperType='" + "ShowDBHMX"
                + "',@UserNo='" + MyApplication.curLoginUserNo + "'";
        Log.e(TAG, SqlComm);
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm, MSG_GetSingINFO);
    }

    //改为API调用
    private void ruKu(String name) {
        hideIM(editBarcode);
        editBarcode.setEnabled(false);
        TaskID = UUID.randomUUID().toString();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("OperType", "GetAgvCallInfo");
            jsonObject.put("FormType", FormType);
            jsonObject.put("DepSiteNo", CurStationNo);
            jsonObject.put("BoxNo", tv_checkout_box_num_show.getText().toString());
            jsonObject.put("BoxType", name);
            jsonObject.put("TaskID", TaskID);
            jsonObject.put("DefaultExit", defaultName);
            jsonObject.put("IsAutoRecognition", isAuto);
            jsonObject.put("UserNo", MyApplication.curLoginUserNo);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        postJsonData(MyApplication.UrlApi + "/api/web/CheckCutInCallWMS", jsonObject.toString(), handler, MSG_CallAgvResult);
    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm, int msgWhat) {
        ScanSign = true;
        if (waitDialog != null) waitDialog.setMessage("正在执行,请稍等....");
        System.out.println("SQLComm:" + SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("haodong--Start");
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    String OperType = "";
                    if (jsonArray != null && jsonArray.length() > 0) {
                        //物料类型加载了明细的
                        if (jsonArray.optJSONObject(0).has("OperType")) {
                            OperType = jsonArray.optJSONObject(0).getString("OperType");
                            if (OperType.equals("LoadTXM")) {
                                TXMdetailJSON = jsonArray;
                                System.out.println("LoadTXM--haodong--Start" + jsonArray.toString());
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_GET_ALL_BOX_NUM;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            } else if (OperType.equals("getPower")) {
                                powerJson = jsonArray;
                                System.out.println("Other--haodong--Start" + jsonArray.toString());
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = msgWhat;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            } else {
                                detailJSON = jsonArray;
                                System.out.println("Other--haodong--Start" + jsonArray.toString());
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = msgWhat;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept")) {
                            Message msg = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putString("HintInfo", jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.what = MSG_ERROR;
                            msg.setData(bundle);
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                    } else {
                        Message msg = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("HintInfo", "后台未返回任何值");
                        msg.what = MSG_ERROR;
                        msg.setData(bundle);
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("haodong--Error" + e.getMessage());
                    //刷新界面;
                    ScanSign = false;
                    Message msg = new Message();
                    msg.what = MSG_AllowScan;
                    msg.obj = e.toString();
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                }

            }

        };
        new Thread(run).start();

    }


    //显示弹窗
    private void showPopWindows(String paramHintInfo, int paramDelaySec, boolean clearOldInfo) {
        int deviationX = 450, deviationY = 550;
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        System.out.println("屏宽:" + dm.widthPixels);
        System.out.println("屏高:" + dm.heightPixels);
        //创建并初始化完成
        //创建并初始化完成
        if (popupWindow == null) {
            popupWindow = new BasePopupWindow(this);
            popupWindow.setWidth(dm.widthPixels / 2);
            popupWindow.setHeight(dm.heightPixels / 3);
        }
        //取视图
        if (inflaterView == null)
            inflaterView = LayoutInflater.from(this).inflate(R.layout.level_pop, null);
        LinearLayout linear_HintPop = inflaterView.findViewById(R.id.linear_HintPop);
        TextView tv_LevelPop = inflaterView.findViewById(R.id.tv_LevelPop);
        if (clearOldInfo) tv_LevelPop.setText(paramHintInfo);
        else tv_LevelPop.setText(paramHintInfo + "\r\n" + tv_LevelPop.getText().toString());
        Button popbtn_close = inflaterView.findViewById(R.id.popbtn_close);
        popbtn_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow.isShowing()) popupWindow.dismiss();
            }
        });
        //显示视图
        popupWindow.setContentView(inflaterView);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));//全透明背景
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.viewSecond = paramDelaySec;//显示5秒，自定义类;
        popupWindow.showAtLocation(mainFrame, Gravity.RIGHT | Gravity.BOTTOM, 0, 0);
    }

    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            hideIM(editBarcode);
            System.out.println("Enter handleMessage:" + msg.what);
            if (waitDialog != null && waitDialog.isShowing()) waitDialog.hide();
            ScanSign = false;
            if (btnView != null) btnView.setEnabled(true);
            editBarcode.setEnabled(true);
            editBarcode.selectAll();
            editBarcode.requestFocus();
            switch (msgId) {
                //获取权限
                case MsgGetPower:
                    if (powerJson != null && powerJson.length() > 0) {
                        Log.e("11111",powerJson.toString());
                        List<PowerBean> list = new ArrayList<>();
                        list.addAll(new Gson().fromJson(String.valueOf(powerJson), new TypeToken<List<PowerBean>>() {
                        }.getType()));
                        if (list != null && list.size() > 0) {
                            for (int i = 0; i < list.size(); i++) {
                                if (list.get(i).getBtnName().equals("tv_one_one")) {
                                    if (list.get(i).getPowerValue()==1)
                                        tv_one_one.setVisibility(View.VISIBLE);
                                    else
                                        tv_one_one.setVisibility(View.INVISIBLE);
                                }
                                if (list.get(i).getBtnName().equals("tv_one_two")) {
                                    if (list.get(i).getPowerValue()==1)
                                        tv_one_two.setVisibility(View.VISIBLE);
                                    else
                                        tv_one_two.setVisibility(View.INVISIBLE);
                                }
                                if (list.get(i).getBtnName().equals("tv_two")) {
                                    if (list.get(i).getPowerValue()==1)
                                        tv_two.setVisibility(View.VISIBLE);
                                    else
                                        tv_two.setVisibility(View.INVISIBLE);
                                }
                                if (list.get(i).getBtnName().equals("tv_three")) {
                                    if (list.get(i).getPowerValue()==1)
                                        tv_three.setVisibility(View.VISIBLE);
                                    else
                                        tv_three.setVisibility(View.INVISIBLE);
                                }
                                if (list.get(i).getBtnName().equals("tv_four")) {
                                    if (list.get(i).getPowerValue()==1)
                                        tv_four.setVisibility(View.VISIBLE);
                                    else
                                        tv_four.setVisibility(View.INVISIBLE);
                                }
                                if (list.get(i).getBtnName().equals("tvCheckoutIn")) {
                                    if (list.get(i).getPowerValue()==1)
                                        tvCheckoutIn.setVisibility(View.VISIBLE);
                                    else
                                        tvCheckoutIn.setVisibility(View.INVISIBLE);
                                }
                                if (list.get(i).getBtnName().equals("tvBeici")) {
                                    if (list.get(i).getPowerValue()==1)
                                        tvBeici.setVisibility(View.VISIBLE);
                                    else
                                        tvBeici.setVisibility(View.INVISIBLE);
                                }
                                if (list.get(i).getBtnName().equals("tv_checkout_in_wei_qi")) {
                                    if (list.get(i).getPowerValue()==1)
                                        tv_checkout_in_wei_qi.setVisibility(View.VISIBLE);
                                    else
                                        tv_checkout_in_wei_qi.setVisibility(View.INVISIBLE);
                                }
                                if (list.get(i).getBtnName().equals("tvSure")) {
                                    if (list.get(i).getPowerValue()==1)
                                        tvSure.setVisibility(View.VISIBLE);
                                    else
                                        tvSure.setVisibility(View.INVISIBLE);
                                }
                            }
                        }
                    }
                    break;
                case MSG_ERROR:
                    Bundle bundle = msg.getData();
                    Toaster.showLong(CheckoutConsoleActivity.this, bundle.getString("HintInfo"));
                    if (tv_checkout_box_num_show.getText().toString().length() == 0)
                        NeedReGetBox = true;
                    break;
                case MSG_SaveError:
                    if (detailJSON != null && detailJSON.length() > 0) {
                        if (detailJSON.optJSONObject(0).has("ResultInfo")) {
                            try {
                                Toaster.showLong(CheckoutConsoleActivity.this, detailJSON.optJSONObject(0).getString("ResultInfo"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        if (detailJSON.optJSONObject(0).has("PrBarcode")) {
                            try {
                                PrBarcode = detailJSON.optJSONObject(0).getString("PrBarcode");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        if (detailJSON.optJSONObject(0).has("ErrInfo") == true) {
                            AlertDialog alertDialog = null; // 创建对话框
                            try {
                                alertDialog = new AlertDialog.Builder(CheckoutConsoleActivity.this)
                                        .setTitle("系统提示").setMessage(detailJSON.optJSONObject(0).getString("ErrInfo"))
                                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                ScanSign = false;
                                                return;
                                            }
                                        }).create();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            alertDialog.show(); // 显示对话框
                        }
                        break;
                    }
                    break;
                case MSG_GetBoxNum:
                    getBoxNum();
                    break;
                case MSG_GET_ALL_BOX_NUM:
                    tv_checkout_box_internal_num_show.setText("--");
                    if ((TXMdetailJSON != null) && (TXMdetailJSON.length() > 0)) {
                        System.out.println("TXMdetailJSON:" + TXMdetailJSON);
                        Gson gson = new Gson();
                        detailList.clear();
                        detailList.addAll(gson.fromJson(String.valueOf(TXMdetailJSON), new TypeToken<List<LoadTXMEntity>>() {
                        }.getType()));
                        System.out.println("detailList Size:" + detailList.size());
                        refreshTXMList();
                        Log.e("wwwwww", detailList.size() + "");
                        if (detailList != null) {
                            tv_checkout_box_internal_num_show.setText(detailList.size() + "");
                        }
                    } else {
                        mListView.setAdapter(null);
                        tv_checkout_box_internal_num_show.setText("0");
                    }
                    break;
                case MSG_CLEAR_BARCODE:
                case MSG_CLEAR_BOX:
                case MSG_FocusBarcode:
                    if (detailJSON != null && detailJSON.length() > 0) {
                        if (detailJSON.optJSONObject(0).has("IsShowError")) {
                            if (detailJSON.optJSONObject(0).has("ResultInfo")) {
                                try {
                                    ShowErrorInput(detailJSON.optJSONObject(0).getString("ResultInfo"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                return;
                            } else {
                                Toaster.showLong(CheckoutConsoleActivity.this, "未找到【ResultInfo】返回,请检查!");
                            }
                            return;
                        }
                    }
                    //searchAllCode();
                case MSG_GetSingINFO:
                    fillScreen(msgId);
                    break;
                case MSG_GET_BOX_NUM:
                    fillScreen(MSG_GET_BOX_NUM);
                    searchAllCode();
                    break;
                case MSG_AgvCallInfoTrans:
                    System.out.println("MSG_GetAgvCallInfo:Enter");
                    prBoxNum = tv_checkout_box_num_show.getText().toString();
                    tv_checkout_box_num_show.setText("");
                    NeedReGetBox = true;
                    break;
                case MSG_CallAgvResult:
                    System.out.println("MSG_CallAgvResult:" + MSG_CallAgvResult);
                    if (msg.arg1 == BaseRequest.HAND_REQUEST_FAILURE) {
                        ResultInfo.setText(ResultInfo.getText().toString() + "\r\n" + "请求失败：" + msg.obj.toString());
                        showPopWindows("请求失败" + msg.obj.toString() + "..", 5, true);
                        return;
                    }
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        String errorinfo = "";
                        int status = 1;
                        if (jsonObject.has("errorinfo"))
                            errorinfo = jsonObject.getString("errorinfo");
                        if (jsonObject.has("status")) status = jsonObject.getInt("status");
                        if (status == 0) {
                            ResultInfo.setText(ResultInfo.getText().toString() + "\r\n" + "呼叫成功" + errorinfo);
                            ResultInfo.setTextColor(getResources().getColor(R.color.green));
                            showPopWindows("呼叫成功:" + errorinfo + "..", 5, true);
                            prBoxNum = tv_checkout_box_num_show.getText().toString();
                            tv_checkout_box_num_show.setText("");
                            NeedReGetBox = true;
                        } else {
                            ResultInfo.setText(ResultInfo.getText().toString() + "\r\n" + "呼叫失败" + errorinfo);
                            ResultInfo.setTextColor(getResources().getColor(R.color.red));
                            showPopWindows("呼叫失败:" + errorinfo + "..", 10, true);
                        }
                    } catch (JSONException e) {
                        ResultInfo.setText(ResultInfo.getText().toString() + "\r\n" + "解析失败：");
                        ResultInfo.setTextColor(getResources().getColor(R.color.red));
                        showPopWindows("解析失败.." + e.getMessage(), 5, false);
                    }
                    break;
                case MSG_AllowScan:
                    ScanSign = false;
                    Toaster.showLong(CheckoutConsoleActivity.this, "连接数据库失败");
                    break;
                default:
                    break;
            }
        }
    };

    private void refreshTXMList() {
        LoadTXMAdapter LoadTXMAdapter = new LoadTXMAdapter(CheckoutConsoleActivity.this, detailList, this);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
        //设置布局管理器为线性布局管理器
        mListView.setLayoutManager(layoutManager);
        mListView.setAdapter(LoadTXMAdapter);

    }

    private void ShowErrorInput(String resultInfo) {
        //创建布局
        LayoutInflater inflater = this.getLayoutInflater();
        final View pull_input = inflater.inflate(R.layout.activity_checkout_pop_errorinput, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        //临时加载
        final TextView tv_HintInfo = pull_input.findViewById(R.id.tv_HintInfo);
        tv_HintInfo.setText(resultInfo);
        final EditText text_ErrInfo = pull_input.findViewById(R.id.text_ErrInfo);
        //创建对话框
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(pull_input).setPositiveButton("标记异常", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        System.out.println("text_ErrInfo.getText().toString():" + text_ErrInfo.getText().toString());
                        if (text_ErrInfo.getText().toString().length() > 0) {
                            SaveError(text_ErrInfo.getText().toString());
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, true);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            return;
                        } else {
                            Toaster.showLong(CheckoutConsoleActivity.this, "请输入异常原因!");
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, false);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                }
        ).setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                hideIM(pull_input);
                try {
                    Field field = null;
                    field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                    field.setAccessible(true);
                    field.set(dialog, true);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag", "取消");
            }
        }).setTitle("系统提示");
        builder.show();
    }

    private void fillScreen(int msgwhat) {
        try {
            if (msgwhat == MSG_GET_BOX_NUM) {
                ResultInfo.setText("");
                if ((detailJSON != null) && (detailJSON.length() > 0)) {
                    if (detailJSON.optJSONObject(0).has("BoxNo")) {
                        if (prBoxNum.equals(detailJSON.optJSONObject(0).getString("BoxNo")) == false) {
                            NeedReGetBox = false;
                            tv_checkout_box_num_show.setText(detailJSON.optJSONObject(0).getString("BoxNo"));
                            //指示灯颜色为绿色
                            tv_runState.setBackground(drawable_green);
                        }
                    }
                    if (detailJSON.optJSONObject(0).has("BoxCountNum")) {
                        tv_checkout_box_internal_num_show.setText(detailJSON.optJSONObject(0).getString("BoxCountNum"));
                    } else {
                        tv_checkout_box_internal_num_show.setText("0");
                    }
                }
            } else if (msgwhat == MSG_FocusBarcode) {
                if ((detailJSON != null) && (detailJSON.length() > 0)) {
                    ResultInfo.setText("");
                    if (detailJSON.optJSONObject(0).has("bbm"))
                        bbm.setText(detailJSON.optJSONObject(0).getString("bbm"));
                    if (detailJSON.optJSONObject(0).has("dDate"))
                        dDate.setText(detailJSON.optJSONObject(0).getString("dDate"));
                    if (detailJSON.optJSONObject(0).has("StyleNo"))
                        StyleNo.setText(detailJSON.optJSONObject(0).getString("StyleNo"));
                    if (detailJSON.optJSONObject(0).has("DBH"))
                        DBH.setText(detailJSON.optJSONObject(0).getString("DBH"));
                    if (detailJSON.optJSONObject(0).has("OrderNo"))
                        OrderNo.setText(detailJSON.optJSONObject(0).getString("OrderNo"));
                    if (detailJSON.optJSONObject(0).has("PO"))
                        PO.setText(detailJSON.optJSONObject(0).getString("PO"));
                    if (detailJSON.optJSONObject(0).has("StyleSort"))
                        StyleSort.setText(detailJSON.optJSONObject(0).getString("StyleSort"));
                    if (detailJSON.optJSONObject(0).has("pssh"))
                        pssh.setText(detailJSON.optJSONObject(0).getString("pssh"));
                    if (detailJSON.optJSONObject(0).has("Color"))
                        Color.setText(detailJSON.optJSONObject(0).getString("Color"));
                    if (detailJSON.optJSONObject(0).has("ColorNo"))
                        ColorNo.setText(detailJSON.optJSONObject(0).getString("ColorNo"));
                    if (detailJSON.optJSONObject(0).has("Number"))
                        Number.setText(detailJSON.optJSONObject(0).getString("Number"));


                    if (detailJSON.optJSONObject(0).has("SIZE"))
                        SIZE.setText(detailJSON.optJSONObject(0).getString("SIZE"));
                    if (detailJSON.optJSONObject(0).has("SumPackNum"))
                        SumPackNum.setText(detailJSON.optJSONObject(0).getString("SumPackNum"));
                    if (detailJSON.optJSONObject(0).has("SumScanPackNum"))
                        SumScanPackNum.setText(detailJSON.optJSONObject(0).getString("SumScanPackNum"));
                    if (detailJSON.optJSONObject(0).has("SumPackNumber"))
                        SumPackNumber.setText(detailJSON.optJSONObject(0).getString("SumPackNumber"));
                    if (detailJSON.optJSONObject(0).has("SumScanPackNumber"))
                        SumScanPackNumber.setText(detailJSON.optJSONObject(0).getString("SumScanPackNumber"));
                    if (detailJSON.optJSONObject(0).has("TxmType"))
                        tv_type.setText(detailJSON.optJSONObject(0).getString("TxmType"));
                    if (detailJSON.optJSONObject(0).has("BtnName"))
                        tv_type_name.setText(detailJSON.optJSONObject(0).getString("BtnName"));
                    if (detailJSON.optJSONObject(0).has("BoxNo"))
                        tv_checkout_box_num_show.setText(detailJSON.optJSONObject(0).getString("BoxNo"));
                    if (detailJSON.optJSONObject(0).has("BoxCountNum")) {
                        tv_checkout_box_internal_num_show.setText(detailJSON.optJSONObject(0).getString("BoxCountNum"));
                    } else {
                        tv_checkout_box_internal_num_show.setText("0");
                    }
                    if (detailJSON.optJSONObject(0).has("Txm"))
                        tv_tiao_xing_ma.setText(detailJSON.optJSONObject(0).getString("Txm"));
                    searchAllCode();
                }
                getSingleInfo();
            } else if (msgwhat == MSG_CLEAR_BARCODE) {
                searchAllCode();
            } else if (msgwhat == MSG_GetSingINFO) {
                if ((detailJSON != null) && (detailJSON.length() > 0)) {
                    Gson gson = new Gson();
                    List<SingleDetailEntity> mdetailList = gson.fromJson(String.valueOf(detailJSON), new TypeToken<List<SingleDetailEntity>>() {
                    }.getType());
                    singleDetailListviewAdapter = new SingleDetailListviewAdapter(CheckoutConsoleActivity.this, mdetailList);
                    lv_single.setAdapter(singleDetailListviewAdapter);
                } else {
                    lv_single.setAdapter(null);
                }
            }
            if ((detailJSON != null) && (detailJSON.length() > 0)) {
                if (detailJSON.optJSONObject(0).has("ResultInfo")) {
                    ResultInfo.setText(detailJSON.optJSONObject(0).getString("ResultInfo"));
                }
                if (detailJSON.optJSONObject(0).has("ErrInfo")) {
                    ResultInfo.setText(detailJSON.optJSONObject(0).getString("ErrInfo"));
                    try {
                        Toaster.showLong(CheckoutConsoleActivity.this, detailJSON.optJSONObject(0).getString("ErrInfo"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if (detailJSON.optJSONObject(0).has("FontColor"))
                    ResultInfo.setTextColor(GetColorValue(detailJSON.optJSONObject(0).getString("FontColor")));
            }

        } catch (JSONException e) {
            Toast.makeText(CheckoutConsoleActivity.this, e.toString(), Toast.LENGTH_LONG).show();
        }

    }


    @Override
    public void onItemClick(int position, String data) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(CheckoutConsoleActivity.this);
        dialog.setTitle("提示");
        dialog.setMessage("是否确定删除");
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                clearBarcode(data);
            }
        });
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            }
        });
        dialog.show();
    }

    //保留英文和数字
    private String dealCode(String code) {
        return code.replaceAll("[^a-zA-Z0-9]", "");
    }

    //发送刷新箱号
    @Override
    public void run() {
        long startTime, endTime;
        float excTime;
        byte recBuffer[] = new byte[128];
        startTime = System.currentTimeMillis();
        //判断需发送的内容;
        while (!ExitSign) {
            if (NeedReGetBox) {
                endTime = System.currentTimeMillis();
                excTime = (float) (endTime - startTime);
                //将无卡灯转为灰色,有卡需等数据读完才转;
                if (excTime > 1500) {
                    Log.d("SysHint", "获取箱号! 0 NeedReGetBox:" + NeedReGetBox + " PrBoxNum:" + prBoxNum);
                    //发送消息给对应的Fragment，提示闪灯或关闭灯;
                    Message msg = new Message();
                    msg.what = MSG_GetBoxNum;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                    startTime = System.currentTimeMillis();
                }
            } else {
                Log.d("SysHint", "系统暂停中! 1 NeedReGetBox:" + NeedReGetBox + " PrBoxNum:" + prBoxNum);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        NeedReGetBox = true;
        ExitSign = false;
        //自动获取箱号
        getBoxNum();
        //循环发送；
        new Thread(this).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (waitDialog != null) waitDialog.dismiss();
        ExitSign = true;
        handler.removeMessages(MSG_GetBoxNum);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (waitDialog != null) waitDialog.dismiss();
        ExitSign = true;
        handler.removeMessages(MSG_GetBoxNum);
    }
}
